package com.basker.pisces.oss.service;

import java.io.File;
import java.text.MessageFormat;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * @author hangwen
 * @date 2020/12/12
 */
class OSSUtils {

    static String generateDownloadUrl(String path) {
        return utf8URLEncode(MessageFormat.format("/oss/download?path={0}", path));
    }

    static String generatePath(String container, String name) {
        Assert.hasText(name, "parameter 'name' is required");

        if (StringUtils.isEmpty(container)) {
            return name;
        } else {
            return container + File.separator + name;
        }
    }

    static String utf8URLEncode(final String text) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);

            if (c >= 0 && c <= 255) {
                result.append(c);
            } else {
                byte[] b = new byte[0];

                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception ex) {

                }

                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k += 256;
                    }
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }

        return result.toString();
    }
}
